package com.ldj.rocketmq.producer;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * User: ldj
 * Date: 2024/3/26
 * Time: 0:28
 * Description: 同步消息生产者 使用场景：重要消息通知，如短信
 */
public class SyncProducer {

    public static void main(String[] args) {
        /*
          套路：
          1. 创建消息生产者producer,并制定生产者组名
          2. 指定NameServer地址
          3. 启动producer
          4. 创建消息对象，指定主题Topic、Tag和消息体
          5. 发送消息
          6. 关闭生产者producer
         */
        DefaultMQProducer producer = new DefaultMQProducer("produce-group1");
        producer.setNamesrvAddr("192.168.126.132:9876;192.168.126.133:9876");
        try {
            producer.start();
            for (int i = 0; i < 10; i++) {
                /*
                   消息对象3个重要参数：
                   1.topic(情书)
                   2.tags(告白、约会、日常)
                   3.msg(书信内容)
                */
                String msg = StringUtils.join("I LOVE YOU ", i + 1);
                Message message = new Message("love_letter", "confession", msg.getBytes(StandardCharsets.UTF_8));
                SendResult result = producer.send(message, 3 * 1000);

                if (Objects.nonNull(result)) {
                    System.out.println("消息Id：" + result.getMsgId()+" "+"消息状态：" +
                            result.getSendStatus()+" "+"Broker名称：" +
                            result.getMessageQueue().getBrokerName()+" "+"消息队列Id：" +
                            result.getMessageQueue().getQueueId());
                }
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            producer.shutdown();
        }
    }
}
